/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlets;

import DTOs.DTORestaurante;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Julian
 */
public class RestaurantsServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        String action = request.getParameter("action");
        HttpSession session = request.getSession();

        if(action==null){
            session.setAttribute("error", "Lo sentimos. Ha ocurrido un error procesando la solicitud.");
            response.sendRedirect("error.jsp");
        }else if(action.equals("searchRestaurants")){
            List<DTOs.DTORestaurante> rlist = new ArrayList<DTOs.DTORestaurante>();
            businessDelegate.BusinessDelegate bd = new businessDelegate.BusinessDelegate();
            try{
                String date = request.getParameter("date");
                rlist = bd.getMesasByDate(date);
                session.setAttribute("restaurantList", rlist);
                session.removeAttribute("notificacionRestaurantes");
                response.sendRedirect("buscarRestaurantes.jsp");
            }catch(Exception e){
                e.printStackTrace();
                response.sendRedirect("index.jsp");
            }
        }else if(action.equals("AgregarPlan")){
            try{
                List<DTOs.DTORestaurante> reserved = (List<DTORestaurante>) session.getAttribute("DTOR");
                List<DTOs.DTORestaurante> lista = (List<DTORestaurante>) session.getAttribute("restaurantList");
                if(reserved != null){
                    System.out.println("Hay algo: "+reserved.size());
                    int id = Integer.parseInt(request.getParameter("id"));
                    String fecha = request.getParameter("fecha");
                    String[] dateSplitted = fecha.split("/");
                    Date fechita = new Date(Integer.parseInt(dateSplitted[2]), Integer.parseInt(dateSplitted[0]), Integer.parseInt(dateSplitted[1]));
                    boolean repeated = false;
                    for(int i=0;i < reserved.size();i++){
                        System.out.println("Fecha de la Lista= " + reserved.get(i).getFecha() + " , fecha traida= " + fechita + " , Id mesa lista= " + reserved.get(i).getIdmesa() + " , id traido = " + id);
                        if(reserved.get(i).getFecha().equals(fechita) && reserved.get(i).getIdmesa() == id){
                            repeated = true;
                            break;
                        }
                    }
                    if(repeated){
                        System.out.println("Esta repetido: "+reserved.size());
                        session.setAttribute("notificacionRestaurantes", "0");
                        response.sendRedirect("buscarRestaurantes.jsp");
                    }else{
                        System.out.println("No esta repetido: "+reserved.size());
                        for(int j=0;j<lista.size();j++){
                            if(lista.get(j).getFecha().equals(fechita) && lista.get(j).getIdmesa() == id){
                                reserved.add(lista.get(j));
                                System.out.println("Se agrego: "+reserved.size());
                                session.setAttribute("DTOR", reserved);
                                break;
                            }
                        }
                        session.setAttribute("notificacionRestaurantes", "1");
                        response.sendRedirect("buscarRestaurantes.jsp");
                    }
                }else{
                    int id = Integer.parseInt(request.getParameter("id"));
                    String fecha = request.getParameter("fecha");
                    String[] dateSplitted = fecha.split("/");
                    List<DTOs.DTORestaurante> reserved1 = new ArrayList<DTOs.DTORestaurante>();
                    Date fechita = new Date(Integer.parseInt(dateSplitted[2]), Integer.parseInt(dateSplitted[0]), Integer.parseInt(dateSplitted[1]));
                    for(int j=0;j<lista.size();j++){
                        System.out.println("Fecha de la Lista= " + lista.get(j).getFecha() + " , fecha traida= " + fechita + " , Id mesa lista= " + lista.get(j).getIdmesa() + " , id traido = " + id);
                        if(lista.get(j).getFecha().equals(fechita) && lista.get(j).getIdmesa() == id){
                            reserved1.add(lista.get(j));
                            session.setAttribute("DTOR", reserved1);
                            break;
                        }
                    }
                    System.out.println("No hay nada: "+reserved1.size());
                    session.setAttribute("notificacionRestaurantes", "1");
                    response.sendRedirect("buscarRestaurantes.jsp");
                }
            }catch(Exception e){
                e.printStackTrace();
                response.sendRedirect("index.jsp");
            }
        }
        
        /*response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet RestaurantsServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet RestaurantsServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
            
        } finally { 
            out.close();
        }*/
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
